package standart;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DatabaseConnect {
	private String driver;
	private String username;
	private String password;

	public DatabaseConnect(String driver, String username, String password) {
		this.driver = driver;
		this.username = username;
		this.password = password;

	}

	public Connection AsquireData() {
		try {
			Properties properties = new Properties();
			properties.setProperty("user", username);
			properties.setProperty("password", password);
			return (DriverManager.getConnection(driver, properties));
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("Couldn't establish the "
					+ "connection to database");
		}
		return null;
	}

	public String CheckCert(Connection conn, String cert) throws SQLException {
		PreparedStatement ps = conn.prepareStatement("Select * from CERT where certificate=?");
		ps.setString(1, cert);
		ResultSet rs = ps.executeQuery();
		int rowCount=0;

		while (rs.next()) {
			++rowCount;
			
			System.out.println(rs.getString(1));
		}

		System.out.println(rowCount);

		if (rowCount >= 1) {
			return "1";
		} else {
			return "-1";
		}
	}

	int addKey(Connection conn, String key) throws SQLException {
		PreparedStatement ps = conn.prepareStatement("Insert into  KeyTable "
				+ "values(call NEXT VALUE FOR SQ_KEY,?)");
		ps.setString(1, key);
		int rowCount = ps.executeUpdate();

		if (rowCount >= 1) {
			System.out.println("Key added successfully");
		} else {
			System.out.println("Key not added properly");
		}
		ps = conn.prepareStatement("Select id from KeyTable where key=?");
		ps.setString(1, key);
		ps.execute();
		ResultSet rs = ps.getResultSet();
		return rs.getInt("id");
	}

	void addCert(Connection conn, String cert) throws SQLException {
		PreparedStatement ps = conn.prepareStatement("Insert into  CertTable "
				+ "values(call NEXT VALUE FOR SQ_ID,?)");
		ps.setString(1, cert);
		int rowCount = ps.executeUpdate();

		if (rowCount >= 1) {
			System.out.println("Certificate added successfully");
		} else {
			System.out.println("Certificate not added properly");
		}
	}
}
